package com.example.config.ribbon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class RestTemplateConfig {

    @Autowired
    private EnhancedTokenInterceptor enhancedTokenInterceptor;

    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加拦截器
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(enhancedTokenInterceptor); // 使用增强的拦截器
        interceptors.addAll(restTemplate.getInterceptors());
        restTemplate.setInterceptors(interceptors);

        return restTemplate;
    }

    @Bean
    @LoadBalanced
    public RestTemplate timeoutRestTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 连接超时 5秒
        factory.setReadTimeout(30000);   // 读取超时 30秒

        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setInterceptors(Arrays.asList(enhancedTokenInterceptor));

        return restTemplate;
    }

}
